package com.h52mm.zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

public class GetDataSample {

    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient=new ZkClient("127.0.0.1:2181");
        System.out.println("ZooKeeper session established");
        String path="/zkclient";
        //判断节点是否存在
        boolean exists = zkClient.exists(path);
        if(!exists){
            //不存在创建节点
            //创建临时节点
            zkClient.createEphemeral(path,"123");
        }

        //注册监听
        zkClient.subscribeDataChanges(path, new IZkDataListener() {
            //节点数据变更
            @Override
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println(path+"该节点内容被更新，更新后的内容"+data);
            }
            //节点删除
            @Override
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path+" 该节点被删除");
            }
        });


        //获取节点内容
        Object o = zkClient.readData(path);
        System.out.println(o);

        //更新
        zkClient.writeData(path,"4567");
        Thread.sleep(1000);
        //删除
        zkClient.delete(path);
        Thread.sleep(1000);

    }

}
